package com.ljkj.cordial.chat.presenter.response;

import android.app.Activity;
import android.text.TextUtils;

import com.lanjiu.lib.imclient.bus.EventConstants;
import com.lanjiu.lib.imclient.bus.MessageEvent;
import com.lanjiu.pro.business.BusinessProtocolEntities;
import com.lanjiu.pro.business.BusinessProtocolMessages;
import com.ljkj.cordial.chat.base.ChatApp;
import com.ljkj.cordial.chat.bean.Canstants;
import com.ljkj.cordial.chat.dao.notify.ChatContentTable;
import com.ljkj.cordial.chat.dao.notify.FriendTable;
import com.ljkj.cordial.chat.util.DeleteHistoryUtil;
import com.ljkj.cordial.chat.util.ObserverThread;

import org.greenrobot.eventbus.EventBus;

public class FriendDeleteProtocolResponse extends AResponseBusinessPresenter {
    @Override
    public void onResponse(Activity activity, boolean isOnScreen, String msgType, Object msg) {
        BusinessProtocolMessages.FriendDeleteProtocol response = (BusinessProtocolMessages.FriendDeleteProtocol) msg;
        if (response.hasRegisteredFriend()) {
            BusinessProtocolEntities.RegisteredFriend friend = response.getRegisteredFriend();
            delAndRefresh(activity, friend.getFriendUserId());
        }
        if (response.hasRegisteredUser()) {
            BusinessProtocolEntities.RegisteredUser friend = response.getRegisteredUser();
            delAndRefresh(activity, friend.getUserId());
        }
        if (response.hasTouristsFriend()) {
            BusinessProtocolEntities.TouristsFriend friend = response.getTouristsFriend();
            delAndRefresh(activity, friend.getFriendUserId());
        }
        if (response.hasTouristsUser()) {
            BusinessProtocolEntities.TouristsUser friend = response.getTouristsUser();
            delAndRefresh(activity, friend.getTemporaryId());
        }
    }

    private void delAndRefresh(Activity activity, String friendUserId) {
        if (!TextUtils.isEmpty(friendUserId) && !ChatApp.getInstance().getUserId().equals(friendUserId)) {
            ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<Integer>() {
                @Override
                public void onAction(Integer obj) {
                    MessageEvent event = MessageEvent.cerateUiRefresh(EventConstants.Action.DELETE_FRIEND);
                    event.setData(friendUserId);
                    EventBus.getDefault().post(event);
                    refresh(activity);
                }

                @Override
                public Integer onThreadAction() {
                    DeleteHistoryUtil.getInstance().deleteNavChat(friendUserId);
                    FriendTable.deleteFriendById(friendUserId);
                    ChatContentTable.deleteById(friendUserId, Canstants.SINGLE_CHAT);
                    return null;
                }
            });

        }
    }
}
